<?php

namespace App\Services\Payment;

use App\Constants\PaymentBusinessScene;
use App\Services\Java\ApiService;
use D1M\Common\Exceptions\BusinessException;
use D1M\Payment\Contracts\Data\CombinedPaymentData;
use D1M\Payment\Service\OrderCheckerInterface;

class OrderChecker implements OrderCheckerInterface
{

    private ApiService $esService;

    /**
     * @param ApiService $esService
     */
    public function __construct(ApiService $esService)
    {
        $this->esService = $esService;
    }

    /**
     * @inheritDoc
     */
    public function check(CombinedPaymentData $combinedPayment)
    {
        $scene = $combinedPayment->getBusinessScene();
        $orderNo = $combinedPayment->getBusinessOrderNo();

        if ($scene == PaymentBusinessScene::PLACING_ORDER) {
            $this->checkOrderState($orderNo);
        } else {
            $this->checkRechargeState($orderNo);
        }
    }

    private function checkOrderState($orderNo)
    {
        $url = '/order/api/order-record/query-state';

        $data = [
            'no' => $orderNo,
        ];

        $result = $this->esService->requestJava($url, $data, 'post');

        if ($result['state'] != 1) {
            throw new BusinessException('订单不是待支付状态，不能支付。订单状态：'
                . $result['state']);
        }
    }

    private function checkRechargeState($orderNo)
    {
        $url = '/card/api/order/queryOrderInfo';

        $data = [
            'id' => $orderNo,
        ];

        $result = $this->esService->requestJava($url, $data, 'post');

        if ($result['state'] != 1) {
            throw new BusinessException('订单不是待支付状态，不能支付。订单状态：'
                . $result['state']);
        }
    }

}